package cn.itcast.nems.manager.icc;

import cn.itcast.nems.manager.auth.KeycloakConfig;
import cn.itcast.nems.manager.auth.KeycloakHelper;
import cn.itcast.nems.manager.icc.model.DictionaryEditModel;
import cn.itcast.nems.manager.icc.model.DictionaryQueryModel;
import cn.itcast.nems.manager.util.ChineseCharacterUtil;
import cn.itcast.nems.manager.util.OkHttpUtil;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class DictionaryV2Manager {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final KeycloakHelper keycloakHelper;
    private final String domain;
    private final String sysClientId ;

    private final String modulePath = "v2/1000/dictionary/";

    public DictionaryV2Manager(String domain, String sysClientId,KeycloakConfig keycloakConfig) {
        logger.info("DictionaryV2Manager init with domain: {} clientId: {}, tokenUrl: {}", domain, keycloakConfig.kcClientId(), keycloakConfig.kcTokenUrl());
        this.keycloakHelper = new KeycloakHelper(keycloakConfig);
        this.domain = domain.endsWith("/") ? domain : domain + "/";
        this.sysClientId = sysClientId ;
    }

    /**
     * 分页查询
     *
     * @param queryModel 参数实体
     * @return 响应正文
     * @throws Exception 异常
     */
    public String findPageList(String queryModel) throws IOException,RuntimeException {
        return OkHttpUtil.doPost(domain + modulePath + "page/list", queryModel, getHeaderMap());
    }

    /**
     * 根据条件查询字典列表
     *
     * @param queryModel 参数实体
     * @return 响应正文
     * @throws Exception 异常
     */
    public String findListByParam(String queryModel) throws IOException,RuntimeException {
        return OkHttpUtil.doPost(domain + modulePath + "list", queryModel, getHeaderMap());
    }
    /**
     * 根据条件查询字典列表
     *
     * @param queryModel 参数实体  实例化方式：DictionaryQueryModel.buildQueryCodeModel(#{parentId},#{code})
     * @return 响应正文
     * @throws Exception 异常
     */
    public String findListByParam(DictionaryQueryModel queryModel) throws Exception {
        return this.findListByParam(JSON.toJSONString(queryModel));
    }

    /**
     * 新增
     *
     * @param editModel 参数实体
     * @return 响应正文
     * @throws Exception 异常
     */
    public String add(DictionaryEditModel editModel) throws IOException,RuntimeException{
        // 如果 code 没有手动设置, 需要通过程序自动生成
        if (!StringUtils.hasText(editModel.getCode())) {
            editModel.setCode(ChineseCharacterUtil.toPinyin(editModel.getName(), Boolean.FALSE));
        }
        return OkHttpUtil.doPost(domain + modulePath + "add", JSON.toJSONString(editModel), getHeaderMap());
    }

    /**
     * 根据ID查询字典信息
     *
     * @param id 字典ID
     * @return 字典详情
     */
    public String findId(Integer id) {
        return OkHttpUtil.doGet(domain + modulePath + +id, getHeaderMap());
    }

    /**
     * 修改
     *
     * @param editModel 参数实体
     * @return 响应正文
     * @throws Exception 异常
     */
    public String update(DictionaryEditModel editModel) throws IOException,RuntimeException {
        // code  一旦生成,禁止修改  [2023-9-18]
        return OkHttpUtil.doPost(domain + modulePath + "update", JSON.toJSONString(editModel), getHeaderMap());
    }

    /**
     * 启用/禁用
     *
     * @param editModel 参数实体
     * @return 响应正文
     * @throws Exception 异常
     */
    public String updateState(DictionaryEditModel editModel) throws IOException,RuntimeException {
        return OkHttpUtil.doPost(domain + modulePath + "state", JSON.toJSONString(editModel), getHeaderMap());
    }

    private Map<String, String> getHeaderMap() {
        String token = "Bearer " + this.keycloakHelper.getAccessToken();
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", token);
        headers.put("sysClientId", sysClientId);
        headers.put("timestamp", String.valueOf(System.currentTimeMillis()));
        headers.put("noncestr", UUID.randomUUID().toString().replace("-",""));
        logger.info("[调用字典接口] 请求参数[authorization]: {}", JSON.toJSONString(headers));
        return headers;
    }
}
